package com.marcjmcd.cop4331;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONObject;

public class Attractions extends Activity
{	
	//Used to send https requests to the google API
	URL url;
	String urlString = "";
	String test = "";
	
	//Private authentication key used to interact with google
	String myKey = "AIzaSyAp24M3GU9V3kWrrezye8CyUrhtpToUhrs";
	
	//Query that determines the types for which to search
	String type = "";
	
	//Coordinates of the user currently
	double currLat = 0.0;
	double currLon = 0.0;
	double lat = 0.0;
	double lon = 0.0;
	
	//Maximum distance to check for local places
	int radius = 0;
	
	//Sensor to tell the API we're not using GPS coordinates
	boolean sensor = false;
	
	//JSON Array that holds the values returned from the website
	JSONArray json = null;
	
    boolean useCurr = false;
	
	LocationManager loc;
	Location location;
	LocationListener ll;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		//Code begins here
		super.onCreate(savedInstanceState);
		setContentView(R.layout.attr);
		
		//Location managers to work with lattitude and longitute coordinates
		loc = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		
		//LocationListener that updates coordinates on location change
		ll = new MyLocationListener();
		
		//Requests updated coordinates
		loc.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, ll);
		
		
		//Buttons
		
		/*
		 * Back - 
		 * 
		 */
		Button back = (Button) findViewById(R.id.button7);
		
		back.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) 
			{
				Context context = getApplicationContext();
					
				//Return to Main
				startActivity(new Intent(context, Main.class));
			}
		});
		
		/*
		 * Food - 
		 * 
		 */
		Button food = (Button) findViewById(R.id.button14);
		
		food.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) 
			{
				type = "restaurant";
				
				//Constructs the urlString
				if(useCurr)
					urlString = stringConstructor(myKey, lat, lon, radius, sensor, type);
				else
				{
					//Here, you must update the lat and lon values according to the location input by the user
					urlString = stringConstructor(myKey, lat, lon, radius, sensor, type);
				}
				
				
				
				//DO HTTPS REQUEST HERE
				urlString = "https://maps.googleapis.com/maps/api/place/search/json?location=-33.8670522,151.1957362&radius=500&types=food&name=harbour&sensor=false&key=AIzaSyAp24M3GU9V3kWrrezye8CyUrhtpToUhrs";
				
				Results res = new Results();
				
				res.execute(urlString);
				//REMOVED CURRENTLY System.out.println(json);
				
				System.out.println(test);
				
			}
		});
		
		/*
		 * Lodging - 
		 * 
		 */			
		Button lodge = (Button) findViewById(R.id.button17);
		
		lodge.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) 
			{
				type = "lodging";
				
				//Constructs the urlString
				if(useCurr)
					urlString = stringConstructor(myKey, lat, lon, radius, sensor, type);
				else
				{
					//Here, you must update the lat and lon values according to the location input by the user
					urlString = stringConstructor(myKey, lat, lon, radius, sensor, type);
				}
				
				try
				{
					url = new URL(urlString);	
				}
				catch(MalformedURLException e)
				{
					System.out.println("URL formed incorrectly! (" + e + ")");
				}
				
				//DO HTTPS REQUEST HERE
			}
		});
	
		/*
		 * Bar - 
		 * 
		 */
		Button bar = (Button) findViewById(R.id.button18);
		
		bar.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) 
			{
				type = "bar";
				
				//Constructs the urlString
				if(useCurr)
					urlString = stringConstructor(myKey, lat, lon, radius, sensor, type);
				else
				{
					//Here, you must update the lat and lon values according to the location input by the user
					urlString = stringConstructor(myKey, lat, lon, radius, sensor, type);
				}
				
				try
				{
					url = new URL(urlString);	
				}
				catch(MalformedURLException e)
				{
					System.out.println("URL formed incorrectly! (" + e + ")");
				}
				
				//DO HTTPS REQUEST HERE
			}
		});
		
		/*
		 * ATM -
		 * 
		 */
		Button atm = (Button) findViewById(R.id.button19);
		
		atm.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) 
			{
				type = "atm";
				
				//Constructs the urlString
				if(useCurr)
					urlString = stringConstructor(myKey, lat, lon, radius, sensor, type);
				else
				{
					//Here, you must update the lat and lon values according to the location input by the user
					urlString = stringConstructor(myKey, lat, lon, radius, sensor, type);
				}
				
				try
				{
					url = new URL(urlString);	
				}
				catch(MalformedURLException e)
				{
					System.out.println("URL formed incorrectly! (" + e + ")");
				}
				
				//DO HTTPS REQUEST HERE
			}
		});
		
		/*
		 * Store -
		 * 
		 */
		Button store = (Button) findViewById(R.id.button20);

		store.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) 
			{
				type = "store";
				
				//Constructs the urlString
				if(useCurr)
					urlString = stringConstructor(myKey, lat, lon, radius, sensor, type);
				else
				{
					//Here, you must update the lat and lon values according to the location input by the user
					urlString = stringConstructor(myKey, lat, lon, radius, sensor, type);
				}
				
				try
				{
					url = new URL(urlString);	
				}
				catch(MalformedURLException e)
				{
					System.out.println("URL formed incorrectly! (" + e + ")");
				}
				
				//DO HTTPS REQUEST HERE
			}
		});
		
		/*
		 * Gas - 
		 * 
		 */
		Button gas = (Button) findViewById(R.id.button21);
		
		gas.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) 
			{
				type = "gas_station";
				
				//Constructs the urlString
				if(useCurr)
					urlString = stringConstructor(myKey, lat, lon, radius, sensor, type);
				else
				{
					//Here, you must update the lat and lon values according to the location input by the user
					urlString = stringConstructor(myKey, lat, lon, radius, sensor, type);
				}
				
				try
				{
					url = new URL(urlString);	
				}
				catch(MalformedURLException e)
				{
					System.out.println("URL formed incorrectly! (" + e + ")");
				}
				
				//DO HTTPS REQUEST HERE
			}
		});
		
		
		
		/*
		 * All - 
		 * 
		 */
		Button all = (Button) findViewById(R.id.button22);
		
		store.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) 
			{
				type = "";
				
				//Constructs the urlString
				if(useCurr)
					urlString = stringConstructor(myKey, lat, lon, radius, sensor, type);
				else
				{
					//Here, you must update the lat and lon values according to the location input by the user
					urlString = stringConstructor(myKey, lat, lon, radius, sensor, type);
				}
				
				try
				{
					url = new URL(urlString);	
				}
				catch(MalformedURLException e)
				{
					System.out.println("URL formed incorrectly! (" + e + ")");
				}
				
				//DO HTTPS REQUEST HERE **HOW DO YOU USE JSON**
				try 
				{
					url.getContent();
				} 
				catch (IOException e) 
				{
					System.out.println("URL I/O Error!" + e);
					
					e.printStackTrace();
				}
			}
		});
	}
	
	/*
	 * Used to handle the event of the checkbox being selected
	 */
	public void onCheckboxClicked(View v)
	{
		Context context = getApplicationContext();
		int duration = Toast.LENGTH_SHORT;
		Toast toast;
		
		if(((CheckBox) v).isChecked())  
		{
			//Tells the java program to use current location values over input location
			useCurr = true;
			
			lat = currLat;
			lon = currLon;
			
			toast = Toast.makeText(context, "(" + lat + ", " + lon + ")", duration);
		}
		else
		{
			useCurr = false;
			
			toast = Toast.makeText(context, "Checkbox Was Unchecked", duration);
		}
		
		//There should NEVER be a case where the checkBox is neither checked nor unchecked
		toast.setGravity(Gravity.BOTTOM, 0, 75);
        toast.show();
			
	}
	
	/*
	 * stringConstructor();
	 * 
	 * Used to generate a GoogleApi-compatible string in order to retrieve data from the servers.  If no type is
	 * specified, then the types field is omitted.
	 * 
	 */
	private String stringConstructor(String key, double lat, double lon, int rad, boolean s, String type)
	{
		String output = "";
		int count = 0;
		
		output += "https://maps.googleapis.com/maps/api/place/search/json?location=" + lat + "," + lon + "&radius=";
		output += rad + "&sensor=" + s + "&key=" + key;
		
		if(!type.equals(""))
			output += "&types=" + type;
		
		return output;
	}
	
	/*
	 * MyLocationListener class that handles changes in location
	 * 
	 */
	private class MyLocationListener implements LocationListener
	{
		   
		public void onLocationChanged(Location location) 
		{
			if(location != null)
			{
				currLon = location.getLongitude();
				currLat = location.getLatitude();
				
				System.out.println( "(" + lat + ", " + lon + ")");
			}
	    }

		@Override
		public void onProviderDisabled(String provider) 
		{
			// TODO Auto-generated method stub
		}

		@Override
		public void onProviderEnabled(String provider) 
		{
			if(location != null)
			{
				currLon = location.getLongitude();
				currLat = location.getLatitude();
				
				System.out.println( "(" + lat + ", " + lon + ")");
			}
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) 
		{
			// TODO Auto-generated method stub
		}
	}
	
	private class Results extends AsyncTask<String, Integer, String>
	{
		//Changed to string
		protected String doInBackground(String...params)
		{
			JSONArray output = null;
			
			/*REMOVED FOR NOW
			try
			{
				url = new URL(params[0]);	
				output = (JSONArray) url.getContent();
			}
			catch(MalformedURLException e)
			{
				e.printStackTrace();
			}
			catch(IOException e)
			{
				e.printStackTrace();
			}
			*/
			return params[0];
		}
		
		protected void onPostExecute(String result)
		{
			//json = result;
			test = result;
		}
	}
}
